#pragma once

#include <iostream>
#include <queue>
#include <pthread.h>

template <class T>
class BlockQueue//阻塞队列
{
    static const int defalutnum = 20;
public:
    BlockQueue(int maxcap = defalutnum)
                :maxcap_(maxcap)
    {
        pthread_mutex_init(&mutex_, nullptr);
        pthread_cond_init(&c_cond_, nullptr);
        pthread_cond_init(&p_cond_, nullptr);
    }

    // 谁来唤醒呢？
    T pop()
    {
        pthread_mutex_lock(&mutex_);
        while(q_.size() == 0)
        {
            pthread_cond_wait(&c_cond_, &mutex_); //重新持有锁
        }
        
        T out = q_.front(); 
        q_.pop();

        pthread_cond_signal(&p_cond_); // pthread_cond_broadcast
        pthread_mutex_unlock(&mutex_);

        return out;
    }

    void push(const T &in)
    {
        pthread_mutex_lock(&mutex_);
        while(q_.size() == maxcap_){ 
            pthread_cond_wait(&p_cond_, &mutex_); //1. 调用的时候，自动释放锁 2.？
        }
        // 1. 队列没满 2.被唤醒 
        q_.push(in);                    
        pthread_cond_signal(&c_cond_);
        pthread_mutex_unlock(&mutex_);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&mutex_);
        pthread_cond_destroy(&c_cond_);
        pthread_cond_destroy(&p_cond_);
    }
private:
    std::queue<T> q_; 
    int maxcap_;      // 极值
    pthread_mutex_t mutex_;
    pthread_cond_t c_cond_;
    pthread_cond_t p_cond_;

};